package com.bjpowernode.controller;

import com.bjpowernode.entity.TPermission;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.query.UserQuery;
import com.bjpowernode.result.Result;
import com.bjpowernode.service.PermissionService;
import com.bjpowernode.service.UserService;
import com.bjpowernode.util.LoginInfoUtil;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    private final PermissionService permissionService;

    /**
     * 查询用户的信息
     */
    @GetMapping("/api/login/user")
    public Result getUserInfo() {
        //从security中获取用户的信息
        TUser currentLoginUser = LoginInfoUtil.getCurrentLoginUser();

        // 查询用户对应的菜单权限
        List<TPermission> tPermissionList = permissionService.selectMenuPermission(currentLoginUser.getId());
        currentLoginUser.setMenuPermissionList(tPermissionList);

        return Result.OK(currentLoginUser);
    }

    /**
     * 分页查询
     * 105
     * 10
     * 11
     */
    @GetMapping("/api/users")
    public Result getUsers(Integer current) {
        PageInfo<TUser> pageInfo = userService.getUserByPage(current);

        return Result.OK(pageInfo);
    }

    /**
     * 查看用户明细
     */
    @GetMapping("/api/user/{id}")
    public Result user(@PathVariable Integer id) {
        TUser tUser = userService.getUserById(id);

        return Result.OK(tUser);
    }

    /**
     * 用户添加
     */
    @PostMapping("/api/user")
    public Result addUser(@Valid UserQuery userQuery) {
        int count = userService.addUser(userQuery);

        return count > 0 ? Result.OK() : Result.FAIL();
    }

    /**
     * 用户修改
     */
    @PutMapping("/api/user")
    public Result updateUser(UserQuery userQuery) {
        int count = userService.updateUser(userQuery);

        return count > 0 ? Result.OK() : Result.FAIL();
    }

    /**
     * 用户删除
     */
    @DeleteMapping("/api/user/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        int count = userService.deleteUser(id);
        return count > 0 ? Result.OK() : Result.FAIL();
    }

    /**
     * 批量删除用户
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/api/users")
    public Result deleteUsers(String ids) {
        //将ids字符串转换成集合
        List<String> idList = Arrays.asList(ids.split(","));

        int count = userService.deleteUsers(idList);
        return count > 0 ? Result.OK() : Result.FAIL();
    }

    /**
     * 查询全部用户信息
     */
    @GetMapping("api/owners")
    public Result owners() {
        List<TUser> tUserList = userService.getOwners();
        return Result.OK(tUserList);
    }
}
